;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GuaranteesOut", [])
        .controller("GuaranteesOutCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, $stateParams) {
            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.datePickerFlag = [false, false, false, false];
            $scope.submitted = false;
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.markInfoCK= {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.orderCondition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            // 已删除的
            $scope.dataDelList = [];
            $scope.pageInfoDel = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.guaranteesBillList = [];
            $scope.selectId = ''; // wangcan：已选的三包出库单id
            $scope.codeNumSum = 0; // wangcan：已选的出库数量
            $scope.detailInfo = {
                headerInfo: {},
                detailList: []
            };
            $scope.codeInfo = {
                headerInfo: {},
                codeList: []
            };
            $scope.steps = {
                curStep: 0,
                list: [{
                    name: '选择三包申请单'
                }, {
                    name: '生成三包出库单'
                }]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/threeGuaranteesOut/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/threeGuaranteesOut/exportAll")
            };
            $scope.outState = [{
                    id: 0,
                    name: "未出库"
                },
                {
                    id: 1,
                    name: "部分出库"
                },
                {
                    id: 2,
                    name: "已出库"
                },
                {
                    id: 3,
                    name: "强制结单"
                }
            ];
            $scope.reverseState = [{
                    id: 0,
                    name: "未冲销"
                },
                {
                    id: 1,
                    name: "待审核"
                },
                {
                    id: 2,
                    name: "审核通过"
                },
                {
                    id: 3,
                    name: "审核驳回"
                }
            ];
            $scope.tableConfig = {
                fixedWidth: 360,
                scrollWidth: 1700,
                tableCol: [
                    {
                        type: "",
                        name: "三包出库单号",
                        dataField: "guaranteesOutNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "三包申请单号",
                        dataField: "purchaseNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "sap预留单号",
                        dataField: "sapOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "内部订单号",
                        dataField: "sapId",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "内部订单号描述",
                        dataField: "sapName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件凭证",
                        dataField: "voucherNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "note",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "guaranteesTypeName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调出仓库",
                        dataField: "outLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outLocationStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "updateStateDateTime",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "过账时间",
                        dataField: "postDate",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "SAP同步状态",
                        dataField: "isSynsapSuccessShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewSapError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "过账状态",
                        dataField: "postingState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "冲销状态",
                        dataField: "isReverseShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车型",
                        dataField: "prodType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车号",
                        dataField: "machineNumber",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单据号",
                        dataField: "crmOrder",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务网点",
                        dataField: "serviceSite",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "使用现场件",
                        dataField: "useOnsiteMaterialShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "打印状态",
                        dataField: "isPrintName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "打印时间",
                        dataField: "printTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 320,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.tbConfDel = {
                scrollWidth: 1700,
                tableCol: [
                    {
                        type: "",
                        name: "三包出库单号",
                        dataField: "guaranteesOutNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: "",
                        clickFn: "viewDetail",
                    },
                    {
                        type: "",
                        name: "三包申请单号",
                        dataField: "purchaseNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "sap预留单号",
                        dataField: "sapOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "内部订单号",
                        dataField: "sapId",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "内部订单号描述",
                        dataField: "sapName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件凭证",
                        dataField: "voucherNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "note",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "guaranteesTypeName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调出仓库",
                        dataField: "outLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outLocationStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "updateStateDateTime",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "过账时间",
                        dataField: "postDate",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "SAP同步状态",
                        dataField: "isSynsapSuccessShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewSapError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "过账状态",
                        dataField: "postingState",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "冲销状态",
                        dataField: "isReverseShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车型",
                        dataField: "prodType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车号",
                        dataField: "machineNumber",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单据号",
                        dataField: "crmOrder",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务网点",
                        dataField: "serviceSite",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "使用现场件",
                        dataField: "useOnsiteMaterialShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "打印状态",
                        dataField: "isPrintName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "打印时间",
                        dataField: "printTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    }
                ]
            };
            $scope.guaranteesBillTbConf = {
                scrollWidth: 830,
                tableCol: [{
                        type: "",
                        name: "三包申请单",
                        dataField: "purchaseNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购金额",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单据号",
                        dataField: "crmOrder",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发货方式",
                        dataField: "deliveryTypeName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "realAuditName",
                        width: 100,
                        isShow: $scope.isNJ,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 1120,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        input: false,
                        clickFn: "intentionDetail",
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        input: false,
                        clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单总数",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "outQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 1320,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    /* wangcan:增加条码列,显示已维护的条码 */
                    {
                        name: "零件条码",
                        width: 150,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        input: false,
                        clickFn: "intentionDetail",
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        input: false,
                        clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单总数",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "outQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "上次出库数量",
                        width: 100,
                        dataField: "lastDeliveryQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "实际出库数量",
                        width: 100,
                        dataField: "realOutQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: "",
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                        isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 1500,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际库存",
                        width: 120,
                        dataField: "enableNum",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        input: false,
                        clickFn: "intentionDetail",
                        inputType: ""
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        input: false,
                        clickFn: "deliveryDetail",
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单总数",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "outQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际出库数量",
                        width: 120,
                        dataField: "realOutQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已过账数量",
                        width: 100,
                        dataField: "postAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件凭证",
                        width: 120,
                        dataField: "voucherNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "使用现场件",
                        width: 100,
                        dataField: "useOnsiteMaterialShow",
                        input: false,
                        inputType: ""
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };
            $scope.outTbConf = {
                scrollWidth: 1000,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "订单总数",
                        width: 100,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已发数量",
                        width: 100,
                        dataField: "outQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "出库数量",
                        width: 100,
                        dataField: "deliveryQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次出库数量",
                        width: 130,
                        dataField: "amount",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "stockLocation",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "出库状态",
                        width: 150,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };

            $scope.codeTbConf = {
                scrollWidth: 480,
                tableCol: [{
                        name: "序号",
                        width: 80,
                        dataField: "no",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "条码",
                        width: 200,
                        dataField: "code",
                        input: true,
                        inputType: "code"
                    },
                    {
                        name: "数量",
                        width: 200,
                        dataField: "codeNum",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.tabFlag = {};

            var btnPermissionCode = {
                guaranteesOutAdd: window.ActionCode.guaranteesOutAdd,
                guaranteesOutEdit: window.ActionCode.guaranteesOutEdit,
                guaranteesOutDel: window.ActionCode.guaranteesOutDel,
                guaranteesOutPrint: window.ActionCode.guaranteesOutPrint,
                guaranteesOutOut: window.ActionCode.guaranteesOutOut,
                guaranteesOutExport: window.ActionCode.guaranteesOutExport,
                guaranteesOutObligateAdd: window.ActionCode.guaranteesOutObligateAdd,
                guaranteesOutObligatePosting: window.ActionCode.guaranteesOutObligatePosting,
                mandatoryFinish: window.ActionCode.guaranteesOutMandatoryFinish,
                guaranteesOutEditTJ: window.ActionCode.guaranteesOutEditTJ, // 判断是否是塔机页面
                guaranteesOutTJSC: window.ActionCode.guaranteesOutTJSC, // 判断是否是塔机页面
            };

            $scope.btnPermission = {
                guaranteesOutAdd: true,
                guaranteesOutEdit: true,
                guaranteesOutDel: true,
                guaranteesOutPrint: true,
                guaranteesOutOut: true,
                guaranteesOutExport: true,
                guaranteesOutObligateAdd: true,
                guaranteesOutObligatePosting: true,
                mandatoryFinish: true,
                guaranteesOutEditTJ: true,
                guaranteesOutTJSC: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                if (index == 0) {
                    initData();
                }
            };

            var materialList = [];

            function initData() {
                $scope.detailInfo = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.toolbarConfig.showMateriel = false;
                $scope.steps.curStep = 0;
                $scope.tabFlag = {};
                materialList = [];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/threeGuaranteesOut/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        item.postDate = $filter("YbDate")(item.postDate, "yyyy-MM-dd HH:mm:ss");
                        item.outLocationStatusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        item.isSynsapSuccessShow = $filter("ProgressStatus")(item.sapStatus, "sap");
                        item.postingState = $filter("ProgressStatus")(item.postStatus, "posting");
                        item.isReverseShow = $filter("ProgressStatus")(item.isReverse, "reverse");
                        item.updateStateDateTime = $filter("YbDate")(item.updateStateDate, 'yyyy-MM-dd HH:mm:ss');
                        item.useOnsiteMaterialShow = $filter("TrueOrFalse")(item.useOnsiteMaterial);
                        item.printTimeShow = $filter("YbDate")(item.printTime, "yyyy-MM-dd HH:mm");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType, type) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.detailTbConf.tableCol, 'enableNum').hidden = $scope.needHide;
                        viewDetail(item, type);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "intentionDetail":
                        intentionDetail(item);
                        break;
                    case "deliveryDetail":
                        deliveryDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function intentionDetail(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.IntentionDetail(param);
            }

            function deliveryDetail(item) {
                var param = {
                    materialsNo: item.materialsNo,
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation,
                    billNo: $scope.detailInfo.headerInfo.guaranteesOutNo
                };
                ybWidget.DeliveryDetail(param);
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: true
                };
            };

            $scope.addReset = function () {
                $scope.orderCondition = {
                    seller: true
                };
            };

            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            function geBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }
            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                geBillIds();
            };

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    $scope.markInfo.allChecked = checkAll($scope.dataList);
                }
                geBillIds();
            };

            function checkAll(list) {
                var selectAllFlag = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.selectAllMeal = function () {
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    item.isChecked = $scope.detailInfo.allCheckedMaterial;
                });
            };
            $scope.selectAllCK = function () {
                const someCK = $scope.detailInfo.detailList.every(item => item.isChecked == true)
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    item.isChecked = !someCK;
                });
                $scope.detailInfo.allChecked = !someCK
            };
            $scope.selectSingleMeal = function (item) {
                if (!item.isChecked) {
                    $scope.detailInfo.allCheckedMaterial = false;
                } else {
                    $scope.detailInfo.allCheckedMaterial = checkAll($scope.detailInfo.detailList);
                }
            };
            $scope.selectSingleCK = function (item) {
                $scope.detailInfo.allChecked = $scope.detailInfo.detailList.every(item => item.isChecked == true)
            };
            $scope.batchDelMateriel = function () {
                const hasSelected = $scope.detailInfo.detailList.some(dd => dd.isChecked)
                if (!hasSelected) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.detailInfo.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.detailInfo.detailList[i].isChecked) {
                            $scope.detailInfo.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.detailInfo.detailList.length === 0) {
                        $scope.detailInfo.allCheckedMaterial = false;
                    }
                });
            };

            $scope.add = function () {
                $scope.tabFlag.type = 0;
                $scope.orderCondition.realAuditName = $scope.isNJ? $scope.curUser.name : undefined;
                getGuaranteesBill(1);
                $scope.changeTab(1);
            };

            function getGuaranteesBill(curPage) {
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/list";
                var param = {};
                param.pageSize = $scope.billPageInfo.pageSize;
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = {};
                param.filters = $scope.orderCondition;
                param.filters.guaraenteesStatus = 2;
                param.filters.outEnable = 1;
                if ($scope.isJCH || $scope.isNY) {
                    param.filters.leaderAuditStatus = 3;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate);
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.guaranteesBillList = resp.value.list;
                });
            }

            $scope.orderSearch = function () {
                getGuaranteesBill();
            };

            $scope.selBill = function (item) {
                $scope.steps.curStep = 1;
                $scope.detailInfo.headerInfo = {};
                $scope.detailInfo.detailList = [];
                ybHttp.Get('device', '/threeGuaranteesPur/item', {
                    id: item.id
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.headerInfo.purId = item.id;
                    $scope.detailInfo.headerInfo.guaranteesTypeName = "三包出库";
                    $scope.detailInfo.headerInfo.purchaseNo = resp.value.headerInfo.purchaseNo;
                    $scope.detailInfo.headerInfo.createId = $scope.curUser.userId;
                    $scope.detailInfo.headerInfo.createName = $scope.curUser.name;
                    $scope.detailInfo.headerInfo.createPartId = $scope.curUser.deptId;
                    $scope.detailInfo.headerInfo.createPartName = $scope.curUser.deptName;
                    $scope.detailInfo.headerInfo.createDate = +new Date();
                    $scope.detailInfo.headerInfo.outLocation = "";
                    $scope.detailInfo.headerInfo.sapId = resp.value.headerInfo.sapId;
                    $scope.detailInfo.headerInfo.sapName = resp.value.headerInfo.sapName;
                    $scope.detailInfo.headerInfo.sapTypeName = resp.value.headerInfo.sapTypeName;
                    $scope.detailInfo.headerInfo.note = resp.value.headerInfo.note;
                    $scope.detailInfo.headerInfo.prodType = resp.value.headerInfo.prodType;
                    $scope.detailInfo.headerInfo.machineNumber = resp.value.headerInfo.machineNumber;
                    $scope.detailInfo.headerInfo.crmOrder = resp.value.headerInfo.crmOrder;
                    $scope.detailInfo.headerInfo.serviceName = resp.value.headerInfo.serviceName;
                    $scope.detailInfo.headerInfo.serviceSite = resp.value.headerInfo.serviceSite;
                    $scope.detailInfo.headerInfo.receiverName = resp.value.headerInfo.receiverName;
                    $scope.detailInfo.headerInfo.receiverPhone = resp.value.headerInfo.receiverPhone;
                    $scope.detailInfo.headerInfo.receiverAddress = resp.value.headerInfo.receiverAddress;
                    $scope.detailInfo.headerInfo.sourceType = resp.value.headerInfo.sourceType;
                    $scope.detailInfo.headerInfo.province = resp.value.headerInfo.province;
                    $scope.detailInfo.headerInfo.provinceCode = resp.value.headerInfo.provinceCode;
                    $scope.detailInfo.headerInfo.city = resp.value.headerInfo.city;
                    $scope.detailInfo.headerInfo.cityCode = resp.value.headerInfo.cityCode;
                    angular.forEach(resp.value.detailList, function (item) {
                        if (item.purchaseQty > item.deliveryQty) {
                            var materielItem = {};
                            materielItem.materialsNo = item.materialsNo;
                            materielItem.materialsDesc = item.materialsDesc;
                            materielItem.unit = item.unit;
                            materielItem.qty = item.purchaseQty;
                            materielItem.outQty = item.deliveryQty;
                            materielItem.lastQty = ybWidget.Minus(item.purchaseQty, item.deliveryQty);
                            materielItem.deliveryQty = ybWidget.Minus(item.purchaseQty, item.deliveryQty);
                            materielItem.stockLocation = item.stockLocation;
                            materielItem.enableNum = item.enableNum;
                            materielItem.stockLocationList = item.stockLocationList;
                            materielItem.deliveryNum = item.deliveryNum;
                            materielItem.intentionNum = item.intentionNum;
                            materielItem.oldDeliveryNum = item.deliveryNum;
                            materielItem.oldEnableNum = item.enableNum;
                            materielItem.deliveryMax = materielItem.deliveryQty;
                            materielItem.useOnsiteMaterial = item.useOnsiteMaterial;
                            materielItem.reservedOrder = item.reservedOrder;
                            // 挖机与农机 需要处理 数量问题
                            if ($scope.isWJ || $scope.isNJ) {
                                var realNum = parseFloat(materielItem.enableNum) - parseFloat(materielItem.deliveryNum);
                                if (realNum <= 0) {
                                    materielItem.deliveryQty = 0;
                                } else if (materielItem.deliveryQty > realNum) {
                                    materielItem.deliveryQty = realNum;
                                }
                            }
                            checkItemStockStatus(item, materielItem.deliveryQty); //检查库存状态，显示出库数量输入框颜色
                            materielItem.qtyStockErrLevel = item.qtyStockErrLevel;
                            materielItem.qtyStockErr = item.qtyStockErr;
                            materielItem.qtyErrMsg = item.qtyErrMsg;
                            $scope.detailInfo.detailList.push(materielItem);
                        }
                    });
                    materialList = angular.copy($scope.detailInfo.detailList);
                });
            };
            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/threeGuaranteesOut/remove";
                var billIds = [];

                if (delType === "single") {
                    billIds.push(billId);
                }

                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }

                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };
            $scope.printBill = function (item) {
                var param = {
                    billId: [item.id],
                    printType: "GuaranteesOut",
                    recordPrint: {
                        billNo: item.guaranteesOutNo
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };
            $scope.batchPrint = function () {
                var billIds = [];
                var billNos = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                        billNos.push($scope.dataList[i].guaranteesOutNo);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "GuaranteesOut",
                    cusInterface: '/threeGuaranteesOut/itemList',
                    cusParam: { ids: billIds },
                    isBatchPrint: true,
                    recordPrint: {
                        billNo: billNos.join(',')
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.printBill4Details = function (item) {
                var param = {
                    printType: "GuaranteesOut",
                    cusInterface: '/threeGuaranteesOut/itemDetail',
                    cusParam: {
                        id: $scope.detailInfo.headerInfo.id,
                        detailIds: [item.id]
                    },
                    recordPrint: {
                        billNo: $scope.detailInfo.headerInfo.guaranteesOutNo
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.batchPrint4Details = function () {
                const selectedIds4Detail = $scope.detailInfo.detailList.filter(d => d.isChecked).map(dm => dm.id);
                if (selectedIds4Detail.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "GuaranteesOut",
                    cusInterface: '/threeGuaranteesOut/itemDetail',
                    cusParam: {
                        id: $scope.detailInfo.headerInfo.id,
                        detailIds: selectedIds4Detail
                    },
                    recordPrint: {
                        billNo: $scope.detailInfo.headerInfo.guaranteesOutNo
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector({
                    needPermit: true
                }).then(function (data) {
                    if (!!$scope.detailInfo.headerInfo.outLocation && (data.warehouseCode !== $scope.detailInfo.headerInfo.outLocation)) {
                        $scope.detailInfo.headerInfo.outArea = "";
                        $scope.detailInfo.headerInfo.sapOutArea = "";
                        angular.forEach($scope.detailInfo.detailList, function (item) {
                            item.stockLocation = "";
                            item.isChecked = false;
                        });
                    }
                    $scope.detailInfo.headerInfo.outLocation = data.warehouseCode;
                    /* wangcan */
                    if (!$scope.btnPermission.guaranteesOutTJSC) {
                        filterMaterial();
                    }
                    findDeliveryNum();
                })
            };
            $scope.clearWarehouse = function () {
                $scope.detailInfo.headerInfo.outLocation = "";
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    item.stockLocation = "";
                });
                $scope.detailInfo.detailList = angular.copy(materialList);
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    item.deliveryNum = item.oldDeliveryNum;
                    item.enableNum = item.oldEnableNum;
                });
            };


            function findDeliveryNum() {
                var service = "device";
                var reqUrl = "/threeGuaranteesPur/findDeliveryNum";
                var param = {};
                param.id = $scope.detailInfo.headerInfo.purId;
                param.warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                param.areaCode  = $scope.detailInfo.headerInfo.outArea
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    if (!resp.value) {
                        return;
                    }
                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        angular.forEach(resp.value, function (itemDetail) {
                            if (item.materialsNo === itemDetail.materialsNo) {
                                item.deliveryNum = itemDetail.deliveryNum;
                                item.enableNum = itemDetail.enableNum;
                                // 查询仓库库存时，记录一下
                                if (!param.areaCode) {
                                  item.oldWarehouse_deliveryNum = item.deliveryNum
                                  item.oldWarehouse_enableNum = item.enableNum
                                }
                                // 挖机与农机 需要处理 数量问题
                                if ($scope.isWJ || $scope.isNJ) {
                                    item.deliveryQty = item.deliveryMax;
                                    var realNum = parseFloat(item.enableNum) - parseFloat(item.deliveryNum);
                                    if (realNum <= 0) {
                                        item.deliveryQty = 0;
                                    } else if (item.deliveryQty > realNum) {
                                        item.deliveryQty = realNum;
                                    }
                                }
                            }
                        });
                        $scope.checkQty(item);
                    });
                    //materialList = $scope.detailInfo.detailList;
                });
            }

            function filterMaterial() {
                var warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                var areaCode = $scope.detailInfo.headerInfo.outArea;
                var material = [];
                console.log(materialList);
                for (var i = 0, len = materialList.length; i < len; i++) {
                    if (!!materialList[i].stockLocationList && materialList[i].stockLocationList.length > 0) {
                        for (var j = 0, lenJ = materialList[i].stockLocationList.length; j < lenJ; j++) {
                            var mWarehouseCode = materialList[i].stockLocationList[j].warehouseCode;
                            var mLocationCode = materialList[i].stockLocationList[j].locationCode;
                            var mAreaCode = materialList[i].stockLocationList[j].areaCode;
                            if (warehouseCode === mWarehouseCode) {
                                if (!!areaCode && areaCode !== mAreaCode) {
                                    continue;
                                }
                                materialList[i].stockLocation = mLocationCode;
                                materialList[i].isChecked = false;
                                material.push(materialList[i]);
                                break;
                            }
                        }
                    }
                }
                $scope.detailInfo.detailList = material;
            }

            $scope.selectArea = function () {
                if (!$scope.detailInfo.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择调出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.headerInfo.outArea = data.areaCode;
                    $scope.detailInfo.headerInfo.sapOutArea = data.sapCode;
                    /* wangcan */
                    if (!$scope.btnPermission.guaranteesOutTJSC) {
                        filterMaterial();
                    }
                    findDeliveryNum()
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                $scope.detailInfo.detailList = materialList;
                angular.forEach($scope.detailInfo.detailList, function (item) {
                  // 没有就不取
                  if (!item.oldWarehouse_deliveryNum && item.oldWarehouse_deliveryNum !== 0) {
                    item.deliveryNum = item.oldDeliveryNum;
                    item.enableNum = item.oldEnableNum;
                    return
                  }
                  item.deliveryNum = item.oldWarehouse_deliveryNum;
                  item.enableNum = item.oldWarehouse_enableNum;
                });
            };
            $scope.scClearArea = function () {
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach($scope.detailInfo.detailList, function (item) {
                  item.deliveryNum = 0;
                  item.enableNum = 0;
                  item.intentionNum = 0;
                  item.stockLocation = "";
                });
            };
           $scope.scClearWarehouse = function () {
                $scope.detailInfo.headerInfo.outLocation = "";
                $scope.detailInfo.headerInfo.outArea = "";
                $scope.detailInfo.headerInfo.sapOutArea = "";
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    item.stockLocation = "";
                    item.deliveryNum = 0;
                    item.enableNum = 0;
                    item.intentionNum = 0;
                    item.stockLocation = "";
                });
                    };
            function getDetail(billId ,type) {
                var service = "device";
                if (type == 'del') {
                    var reqUrl = "/threeGuaranteesOut/itemWithDel"; // 已删除详情
                }else {
                    var reqUrl = "/threeGuaranteesOut/item"; // 正常数据详情
                }
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editData = function (item) {
                $scope.selectId = item.id;
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.detailInfo = data;

                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.deliveryNum = item.deliveryNum - item.deliveryQty;
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        item.lastQty = ybWidget.Plus(ybWidget.Minus(item.qty, item.outQty), item.deliveryQty);
                        item.lastDeliveryQty = item.deliveryQty;
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        checkItemStockStatus(item, item.deliveryQty);
                    });
                    $scope.changeTab(2);
                })
            };

            $scope.obligate = function (item) {
                item.obligateDisabled = true;
                var service = "device";
                var reqUrl = "/warehouseInventory/createObligateOrder";
                var param = {};
                param.id = item.id;
                param.businessOrder = item.guaranteesOutNo;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.obligateDisabled = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.posting = function (item, materialsNo) {
                ybWidget.ShowMessage("确定要过账吗？", MESG_TYPE.Ask).then(function () {
                    item.postingDisabled = true;
                    var service = "device";
                    var reqUrl = "/warehouseInventory/obligatePosting";
                    var param = {};
                    param.businessOrder = item.guaranteesOutNo;
                    param.materialsNo = materialsNo;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            item.postingDisabled = false;
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item.id).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.deliveryRevoke = function (item, materialsNo) {
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/warehouseInventory/deliveryRevoke";
                    var param = {
                        businessOrder: item.guaranteesOutNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item.id).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            function viewDetail(item, type) {
                getDetail(item.id, type).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;

                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        item.useOnsiteMaterialShow = $filter("TrueOrFalse")(item.useOnsiteMaterial);
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    if (type) {
                        $scope.changeTab(7);
                    }else {
                        $scope.changeTab(3);
                    }

                })
            }

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            $scope.checkQty = function (item) {
                item.deliveryQtyErr = false;
                if (item.deliveryQty === "") {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "出库数量不能为空";
                    // return;
                }
                if (item.deliveryQty > 99999.999) {
                    item.deliveryQty = 99999.999;
                }
                if (parseFloat(item.deliveryQty) > parseFloat(item.lastQty)) {
                    item.deliveryQtyErr = true;
                    item.deliveryQtyErrMsg = "出库数量不能大于剩余数量";
                    // return;
                }
                checkItemStockStatus(item, item.deliveryQty)
            };

            function checkItemStockStatus(item, currentQty) {
                UserContextService.SetStockStatusFlag(item, currentQty);
            }

            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    // item.deliveryQtyErr = true;
                    item.showStockErr = true;
                }
            };

            $scope.hideQtyTip = function (item) {
                // item.deliveryQtyErr = false;
                item.showStockErr = false;
            };

            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.detailInfo.detailList.length; i < len; i++) {
                    if (!$scope.detailInfo.detailList[i].deliveryQty || $scope.detailInfo.detailList[i].deliveryQty === '0') {
                        isValid = false;
                        $scope.detailInfo.detailList[i].deliveryQtyErr = true;
                        $scope.detailInfo.detailList[i].deliveryQtyErrMsg = "出库数量不能为空或0";
                        break;
                    }
                    if (parseInt($scope.detailInfo.detailList[i].deliveryQty) > parseInt($scope.detailInfo.detailList[i].lastQty)) {
                        isValid = false;
                        $scope.detailInfo.detailList[i].deliveryQtyErr = true;
                        $scope.detailInfo.detailList[i].deliveryQtyErrMsg = "出库数量不能大于剩余数量";
                        break;
                    }
                }
                return isValid;
            }

            $scope.mandatoryFinish = function (billNo, billId, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/threeGuaranteesOut/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;

                                angular.forEach($scope.detailInfo.detailList, function (item) {
                                    item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                                });
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.checkCodeNum = function (item) {
                item.checkCodeNumErr = false;
                if (item.codeNum === "") {
                    item.checkCodeNumErr = true;
                    item.checkCodeNumErrMsg = "数量不能为空";
                    return;
                }
                if (item.codeNum > 99999) {
                    item.codeNum = 99999;
                }
            };

            $scope.addRow = function () {
                var codeItem = {};
                codeItem.no = $scope.codeInfo.codeList.length + 1;
                codeItem.code = '';
                codeItem.codeNum = null;
                $scope.codeInfo.codeList.push(codeItem);
            }

            $scope.selectCode = function (item) {
                ybWidget.CodeSelector().then(function (data) {
                    // if (!!$scope.detailInfo.headerInfo.outLocation && (data.warehouseCode !== $scope.detailInfo.headerInfo.outLocation)) {
                    //     $scope.detailInfo.headerInfo.outArea = "";
                    //     $scope.detailInfo.headerInfo.sapOutArea = "";
                    //     angular.forEach($scope.detailInfo.detailList, function (item) {
                    //         item.stockLocation = "";
                    //         item.isChecked = false;
                    //     });
                    // }
                    item.code = data.warehouseCode;
                })
            };
            $scope.clearCode = function (item) {
                item.code = "";
            };

            $scope.codeSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: $scope.codeInfo.headerInfo,
                    codeList: []
                };
                var errorCount = 0;
                // 增加校验：条码数量是否等于零件数量，大于报错“条码数量不能大于出库总数”
                // 小于提醒：“条码数量小于出库数量，是否保存”；
                $scope.codeNumSum = 0;
                angular.forEach($scope.codeInfo.codeList, function (item) {
                    var listRow = {};
                    listRow.no = item.no;
                    listRow.codeNum = item.codeNum;
                    listRow.code = item.code;
                    /* 只有当条码和数量都存在的时候才会传到列表中 */
                    if (!!listRow.codeNum && !!listRow.code) {
                        $scope.codeNumSum = parseInt($scope.codeNumSum) + parseInt(item.codeNum);
                        param.codeList.push(listRow);
                    }
                    item.codeErr = false;
                    if ((!item.code && item.codeNum) || (item.code && !item.codeNum)) {
                        item.codeErr = true;
                        errorCount++;
                    }
                });
                if ($scope.codeNumSum > $scope.codeInfo.headerInfo.deliveryQty) {
                    ybWidget.ShowToaster('error', '条码数量不能大于出库总数');
                    return;
                } else if ($scope.codeNumSum > $scope.codeInfo.headerInfo.deliveryQty) {
                    ybWidget.ShowToaster('warning', '条码数量小于出库数量，请检查是否要继续保存数据');
                }
                if (errorCount > 0) {
                    ybWidget.ShowToaster('error', '请检查条码是否都已正确填写');
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.cancelCodeInput(); // 回到编辑页：加载页面数据
                });
            };

            /* 取消条码编辑，返回编辑页 */
            $scope.cancelCodeInput = function () {
                getDetail($scope.selectId).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.deliveryNum = item.deliveryNum - item.deliveryQty;
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        item.lastQty = ybWidget.Plus(ybWidget.Minus(item.qty, item.outQty), item.deliveryQty);
                        item.deliveryQty = $scope.codeNumSum;
                        item.lastDeliveryQty = item.deliveryQty;
                        checkItemStockStatus(item, item.deliveryQty);
                    });
                    $scope.changeTab(2);
                })
            }

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }

                if (!!$scope.detailInfo && $scope.detailInfo.detailList.length === 0) {
                    ybWidget.ShowMessage("无零件时无法提交", MESG_TYPE.Error);
                    return;
                }

                if (isErrorStockStatusForExcavatorCompany()) {
                    return;
                }

                var service = "device";
                var reqUrl = "/threeGuaranteesOut/add";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/threeGuaranteesOut/update";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            function isErrorStockStatusForExcavatorCompany() {
                // 暂时 农机使用这种配置
                if ($scope.isNJ) {
                  if (!UserContextService.NeedCheckStockQty('三包出库', $scope.curOrgId)) {
                    return false;
                  }
                } else {
                    if (!($scope.isWJ || $scope.isKJ)) {
                      return false;
                    }
                }

                for (var i = 0; i < $scope.detailInfo.detailList.length; i++) {
                    checkItemStockStatus($scope.detailInfo.detailList[i], $scope.detailInfo.detailList[i].deliveryQty);
                    // wangcan:库存校验
                    /* wangcan:按钮权限码判断是否验证默认储位 */
                    /* 农机默认校验库存数量 */
                    if ($scope.isNJ || !$scope.btnPermission.guaranteesOutTJSC) {
                        if ($scope.detailInfo.detailList[i].qtyStockErr && ($scope.detailInfo.detailList[i].qtyStockErrLevel > 1)) {
                            ybWidget.ShowMessage("零件" + $scope.detailInfo.detailList[i].materialsNo + "，" + $scope.detailInfo.detailList[i].materialsDesc + "库存不足，单据不能创建，请先删除该零件或取消提交", MESG_TYPE.Error);
                            $scope.clickValue = false;
                            return true;
                        }
                    }
                }
                return false;

            }

            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.outbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.detailList, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.outLocationStatus, "outDepot");
                        item.amount = (item.deliveryQty - item.realOutQty) > 0 ? (item.deliveryQty - item.realOutQty) : 0
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.changeTab(4);
                });
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.headerInfo.outLocation
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.stockLocation = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.stockLocation = "";
            };
            $scope.delHistory = function (curPage) {
                $scope.tabFlag.type = 6;
                $scope.changeTab(6);
                var service = "device";
                var reqUrl = "/threeGuaranteesOut/list"
                var param = {}
                param.pageSize = $scope.pageInfoDel.pageSize;
                if (!!curPage) {
                    $scope.pageInfoDel.curPage = curPage;
                }
                param.pageNum = $scope.pageInfoDel.curPage;
                param.filters = angular.copy($scope.condition);
                param.filters.isProcessing = null;
                param.filters.isDel = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        if (item.type === 0) {
                            item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        }
                        if (item.type === 1) {
                            item.statusShow = $filter("ProgressStatus")(item.status, "outDepot");
                        }
                        item.sapStatusShow = $filter("ProgressStatus")(item.sapStatus, "sap");
                        item.postOutStatus = $filter("ProgressStatus")(item.postOutStatus, "posting");
                        item.postInStatus = $filter("ProgressStatus")(item.postInStatus, "posting");
                        item.receiptStatusShow = $filter("ProgressStatus")(item.isReceipt, "receiptState");
                        item.auditStatusShow = $filter("AuditStatus2")(item.auditStatus);
                        item.auditDateShow = $filter("YbDate")(item.auditDate, "yyyy-MM-dd HH:mm:ss");
                        item.printTimeShow = $filter("YbDate")(item.printTime, "yyyy-MM-dd HH:mm");
                    });
                    $scope.pageInfoDel.totalRows = resp.value.total;
                    $scope.pageInfoDel.totalPages = resp.value.pages;
                    $scope.dataDelList = resp.value.list;
                });
            };
            $scope.outboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.guaranteesOutNo;
                const hasSelected = $scope.detailInfo.detailList.filter(dd => dd.isChecked)
                if (hasSelected.length < 1) {
                    ybWidget.ShowMessage('请选择需要出库的行');
                    return;
                }
                const amount = hasSelected.some(dd => dd.amount <=0)
                if (amount) {
                    ybWidget.ShowMessage('有选中的行,本次出库数量未填写');
                    return;
                }
                angular.forEach(hasSelected, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.amount = item.amount;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.stockLocation;
                    item.locationErr = false;
                    if ((item.outLocationStatus === null || item.outLocationStatus === 0 || item.outLocationStatus === 1) && !item.stockLocation) {
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errorCount > 0) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.batchPosting = function() {
                const conditionList = $scope.dataList.filter(df => df.isChecked).map(dm => {
                    return {
                        businessOrder: dm.guaranteesOutNo,
                        inOut: 1,
                    }
                })

                if (conditionList.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要批量过账吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', '/warehouseInventory/obligatePostingBatch', conditionList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.batchReserve = function() {
                const conditionList = $scope.dataList.filter(df => df.isChecked).map(dm => {
                    return {
                        businessOrder: dm.guaranteesOutNo,
                        id: dm.id,
                    }
                })

                if (conditionList.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要批量创建预留吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', '/warehouseInventory/createObligateOrderBatch', conditionList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            (function () {

                if (!!$stateParams.id) {
                    $scope.tabFlag.type = 0;
                    $scope.changeTab(1);
                    $scope.selBill($stateParams)
                } else {
                    $scope.condition.createName = $scope.isJCH ? $scope.curUser.name : undefined;
                    getDataList();
                }
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
